//
//  GroupInfoViewController.m
//  Findif
//
//  Created by Mac on 2019/2/22.
//  Copyright © 2019年 Cicel Chen. All rights reserved.
//

#import "GroupInfoViewController.h"
#import "GroupInfoHeaderView.h"
#import "AddContactsTableViewCell.h"
#import "GroupItemsTableViewCell.h"
#import "GroupFunctionTableViewCell.h"
#import "OutButtonTableViewCell.h"
#import "TopicViewController.h"
#import "GroupActiveViewController.h"
#import "GroupNoticeViewController.h"
#import "EditGroupInfoViewController.h"
#import "GroupMemberViewController.h"
#import "PersonalViewController.h"
#import "InviteGroupMemberViewController.h"
#import "PushNewsViewController.h"
#import "MyAlbumViewController.h"
#import <JMessage/JMessage.h>
#import "ChatViewController.h"
#import "ServerStatementViewController.h"

@interface GroupInfoViewController ()<UITableViewDelegate,UITableViewDataSource,GroupInfoHeaderViewDelegate,GroupFunctionTableViewDelegate,GroupItemsTableViewCellDelegate,OutButtonTableViewCellDelegate>

@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, strong)GroupInfoHeaderView * header;
@property (nonatomic, strong)NSDictionary * dataDict;
@property (nonatomic, strong)NSArray * membersArray;
//用户社团身份 1为社长  0为普通用户  2为游客
@property (nonatomic, copy)NSString * group_user_identity;

@end

@implementation GroupInfoViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self loadData];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    [self setupUI];
}


- (void)loadData{
    
    NSString * user_id = DEF_GET_OBJECT(@"id");
    
    if (self.group_id) {
        
        NSDictionary * dict = @{@"id":self.group_id,@"user_id":user_id};
        [[ZRNetworkTool sharedTool] getGroupInfoWithDict:dict WithBlock:^(BOOL success, id responseData) {
            
//            NSLog(@"res===%@",responseData);
            if (success) {
                
                self.dataDict = responseData[@"data"];
                self.group_user_identity = [NSString stringWithFormat:@"%@",self.dataDict[@"group_user_identity"]];
                self.group_jg_gid = [NSString stringWithFormat:@"%@",self.dataDict[@"group_jg_gid"]];
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseData[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }];
        
        [[ZRNetworkTool sharedTool] getGroupMembersListWithGroup_id:self.group_id WithBlock:^(BOOL success, id responseData) {
            
            //        NSLog(@"res===%@",responseData);
            if (success) {
                
                self.membersArray = responseData[@"data"];
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseData[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }];
    }else if (self.group_jg_gid){
        
        NSDictionary * dict = @{@"group_jg_gid":self.group_jg_gid,@"user_id":user_id};
        
        [[ZRNetworkTool sharedTool] getGroupInfoWithDict:dict WithBlock:^(BOOL success, id responseData) {
            
//            NSLog(@"res===%@",responseData);
            if (success) {
                
                self.dataDict = responseData[@"data"];
                self.group_id = [NSString stringWithFormat:@"%@",self.dataDict[@"id"]];
                self.group_user_identity = [NSString stringWithFormat:@"%@",self.dataDict[@"group_user_identity"]];
                
                [[ZRNetworkTool sharedTool] getGroupMembersListWithGroup_id:self.group_id WithBlock:^(BOOL success, id responseData) {
                    
                    //        NSLog(@"res===%@",responseData);
                    if (success) {
                        
                        self.membersArray = responseData[@"data"];
                    }else{
                        
                        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                       message:responseData[@"message"]
                                                                                preferredStyle:UIAlertControllerStyleAlert];
                        
                        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                              handler:^(UIAlertAction * action) {
                                                                                  
                                                                              }];
                        
                        [alert addAction:defaultAction];
                        [self presentViewController:alert animated:YES completion:nil];
                    }
                }];
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseData[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }];
    }
    
}


- (void)setDataDict:(NSDictionary *)dataDict{
    
    _dataDict = dataDict;
    
    self.header.dict = dataDict;
    [self.tableView reloadData];
}


- (void)setMembersArray:(NSArray *)membersArray{
    
    _membersArray = membersArray;
    
    [self.tableView reloadData];
}


- (void)setupUI{
    
    self.view.backgroundColor = ColorWithRGB(0xF4F5F6);
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = ColorWithRGB(0xF4F5F6);
//    tableView.rowHeight = 120 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator = NO;
    if (@available(iOS 11.0, *)) {
        tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.tableView = tableView;
    
    [self.tableView registerClass:[AddContactsTableViewCell class] forCellReuseIdentifier:@"GroupInfoCell"];
    [self.tableView registerClass:[GroupItemsTableViewCell class] forCellReuseIdentifier:@"GroupItemsTableViewCell"];
    [self.tableView registerClass:[GroupFunctionTableViewCell class] forCellReuseIdentifier:@"GroupFunctionTableViewCell"];
    [self.tableView registerClass:[OutButtonTableViewCell class] forCellReuseIdentifier:@"OutButtonTableViewCell"];
    [self.tableView registerClass:[GroupInfoHeaderView class] forHeaderFooterViewReuseIdentifier:@"GroupInfoHeaderView"];
    
//    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        
//        [self loadData];
//    }];
    
    [self.view addSubview:self.tableView];
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if ([self.group_user_identity isEqualToString:@"1"]) {
        //社长
        return 6;
    }else if ([self.group_user_identity isEqualToString:@"2"]) {
        //游客
        return 3;
    }else{
        
        return 5;
    }
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (section == 0) {
        
        if ([self.group_user_identity isEqualToString:@"1"] || [self.group_user_identity isEqualToString:@"0"]) {
            
            return 2;
        }else{
            
            return 1;
        }
        
    }else if (section == 2){
        
        if ([self.group_user_identity isEqualToString:@"1"]) {
            
            return 2;
        }else{
            
            return 1;
        }
    }else{
        
       return 1;
    }
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            
            GroupItemsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GroupItemsTableViewCell" forIndexPath:indexPath];
            
            //        cell.model = self.goodlistArray[indexPath.row];
            cell.memberArray = self.membersArray;
            cell.countLabel.text = [NSString stringWithFormat:@"共%lu人",(unsigned long)self.membersArray.count];
            cell.type = self.group_user_identity;
            cell.delegate = self;
            
            return cell;
        }else{
           
            AddContactsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GroupInfoCell" forIndexPath:indexPath];
            
            cell.titleLabel.text = @"分享社团";
            cell.subLabel.hidden = YES;
            cell.billSwitch.hidden = YES;
            
            return cell;
        }
        
    }else if (indexPath.section == 1) {
        
        GroupFunctionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GroupFunctionTableViewCell" forIndexPath:indexPath];
        
        cell.delegate = self;
        
        return cell;
    }else if (indexPath.section == tableView.numberOfSections - 1) {
        
        OutButtonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OutButtonTableViewCell" forIndexPath:indexPath];
        cell.delegate = self;
        if ([self.group_user_identity isEqualToString:@"1"]) {
            
            cell.string = @"解散社团";
        }else if ([self.group_user_identity isEqualToString:@"0"]){
            
            cell.string = @"退出社团";
        }else if ([self.group_user_identity isEqualToString:@"2"]){
            
            cell.string = @"加入社团";
        }
        
        return cell;
    }else{
        
        AddContactsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GroupInfoCell" forIndexPath:indexPath];
        
        if (indexPath.section == tableView.numberOfSections - 3){

            cell.titleLabel.text = @"清空聊天记录";
            cell.billSwitch.hidden = YES;
            cell.rightImageView.hidden = NO;
            cell.subLabel.hidden = YES;
        }else if (indexPath.section == tableView.numberOfSections - 2){
            
            cell.titleLabel.text = @"消息免打扰";
            cell.billSwitch.hidden = NO;
            cell.rightImageView.hidden = YES;
            cell.subLabel.hidden = YES;
            cell.status = [NSString stringWithFormat:@"%@",self.dataDict[@"is_touser"]];
            cell.group_id = self.group_id;
        }else {
            
            if (indexPath.row == 0) {
                cell.titleLabel.text = @"编辑资料";
                cell.rightImageView.hidden = NO;
                cell.billSwitch.hidden = YES;
                cell.subLabel.hidden = YES;
            }else{
                
                cell.titleLabel.text = @"社长特权";
                cell.rightImageView.hidden = NO;
                cell.billSwitch.hidden = YES;
                cell.subLabel.hidden = YES;
            }
            
        }
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            
            return  130 * SCREENH6;
        }else{
            
           return 50 * SCREENH6;
        }
        
    }else if(indexPath.section == 1){
        
        return 80 * SCREENH6;
    }else if(indexPath.section == 5){
        
        return 90 * SCREENH6;
    }else{
        
        return 50 * SCREENH6;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        
       return topHeight + 150 * SCREENH6;
    }else{
        
        return 10 * SCREENH6;
    }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    if (section == 0) {
        
        self.header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"GroupInfoHeaderView"];
        
        self.header.delegate = self;
        
        return self.header;
    }else{
        
        UIView * view = [UIView new];
        
        view.backgroundColor = ColorWithRGB(0xF4F5F6);
        
        return view;
    }
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HiddenBar;
    if (indexPath.section == 0){
        
        if (indexPath.row == 0) {
            
            GroupMemberViewController * memberVC = [GroupMemberViewController new];
            
            memberVC.group_id = self.group_id;
            memberVC.identity = self.group_user_identity;
            
            [self.navigationController pushViewController:memberVC animated:YES];
        }else{
            
            PushNewsViewController * pushVC = [PushNewsViewController new];
            
            pushVC.groupString = self.dataDict[@"group_name"];
            pushVC.groupID = [NSString stringWithFormat:@"%@",self.dataDict[@"id"]];
            pushVC.type = @"info";
            
            [self.navigationController pushViewController:pushVC animated:YES];
        }
    }else if (indexPath.section == tableView.numberOfSections - 3){
        //清空聊天记录
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"清空聊天记录"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                                  JMSGConversation * conversation = [JMSGConversation groupConversationWithGroupId:self.group_jg_gid];
                                                                  
                                                                  [conversation deleteAllMessages];
                                                              }];
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
        
    }
    
    if ([self.group_user_identity isEqualToString:@"1"]) {
        
        if (indexPath.section == 2) {
            
            if (indexPath.row == 0) {
                
                EditGroupInfoViewController * editVC = [EditGroupInfoViewController new];
                
                editVC.dict = self.dataDict;
                
                [self.navigationController pushViewController:editVC animated:YES];
            }else{
                
                ServerStatementViewController * stateVC = [ServerStatementViewController new];
                
                stateVC.url = @"https://findif.cn/president.html";
                stateVC.titleStr = @"社长特权";
                
                [self.navigationController pushViewController:stateVC animated:YES];
            }
            
        }
    }
}


- (void)clickFunctionButtonWithType:(NSString *)type{
    
    HiddenBar;
    
    if ([type isEqualToString:@"topic"]) {
        
        TopicViewController * topicVC = [TopicViewController new];
        
        topicVC.group_id = self.group_id;
        topicVC.identity = self.group_user_identity;
        
        [self.navigationController pushViewController:topicVC animated:YES];
    }else if ([type isEqualToString:@"active"]){
        
        GroupActiveViewController * groupVC = [GroupActiveViewController new];
        
        groupVC.group_id = self.group_id;
        groupVC.identity = self.group_user_identity;
        
        [self.navigationController pushViewController:groupVC animated:YES];
    }else if ([type isEqualToString:@"notice"]){
        
        if ([self.group_user_identity isEqualToString:@"2"]) {
            //游客
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"你还不是社团成员，快申请加入社团吧~~"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            GroupNoticeViewController * noticeVC = [GroupNoticeViewController new];
            
            noticeVC.group_id = self.group_id;
            noticeVC.identity = self.group_user_identity;
            
            [self.navigationController pushViewController:noticeVC animated:YES];
        }
    }else if ([type isEqualToString:@"album"]){
        
        if ([self.group_user_identity isEqualToString:@"2"]) {
            //游客
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"你还不是社团成员，快申请加入社团吧~~"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            
            MyAlbumViewController * albumVC = [MyAlbumViewController new];
            
            albumVC.type = @"3";
            albumVC.group_id = self.group_id;
            
            [self.navigationController pushViewController:albumVC animated:YES];
        }
        
    }
}

- (void)clickMembersButtonWithTag:(NSString *)tag{
    
    NSString * user_id = DEF_GET_OBJECT(@"id");
    
    if ([user_id isEqualToString:tag]) {
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"你不能点击自己的头像"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }else if ([tag isEqualToString:@"1"]){
        
        HiddenBar;
        
        InviteGroupMemberViewController * inviteVC = [InviteGroupMemberViewController new];
        inviteVC.group_id = self.group_id;
        [self.navigationController pushViewController:inviteVC animated:YES];
        
    }else{
        
        HiddenBar;
        
        PersonalViewController * personVC = [PersonalViewController new];
        personVC.ID = tag;
        
        [self.navigationController pushViewController:personVC animated:YES];
    }
    
}

- (void)clickOutButton{
    
    ShowHUD;
    if ([self.group_user_identity isEqualToString:@"1"]) {
        //解散社团
        [[ZRNetworkTool sharedTool] deleteGroupWithGroup_id:self.group_id WithBlock:^(BOOL success, id responseData) {
            HiddenHUD;
            if (success) {
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseData[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                        
//                                                                          JMSGConversation * conversation = [JMSGConversation groupConversationWithGroupId:self.group_jg_gid];
//
//                                                                          [conversation deleteAllMessages];
                                                                          
                                                                          for (UIViewController *controller in self.navigationController.viewControllers) {
                                                                              if ([controller isKindOfClass:[ChatViewController class]]) {
                                                                                  ChatViewController *A =(ChatViewController *)controller;
                                                                                  [self.navigationController popToViewController:A animated:YES];
                                                                              }
                                                                          }
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseData[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                          
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }];
    }else if ([self.group_user_identity isEqualToString:@"0"]){
        //退出社团
        [[ZRNetworkTool sharedTool] exitGroupWithGroup_id:self.group_id WithBlock:^(BOOL success, id responseData) {
            HiddenHUD;
            if (success) {
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseData[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                          for (UIViewController *controller in self.navigationController.viewControllers) {
                                                                              if ([controller isKindOfClass:[ChatViewController class]]) {
                                                                                  ChatViewController *A =(ChatViewController *)controller;
                                                                                  [self.navigationController popToViewController:A animated:YES];
                                                                              }
                                                                          }
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseData[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                          
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }];
    }else if ([self.group_user_identity isEqualToString:@"2"]){
        //加入社团
        [[ZRNetworkTool sharedTool] applyForJoinGroupWithGroup_id:self.group_id WithBlock:^(BOOL success, id responseData) {
            HiddenHUD;
            if (success) {
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseData[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                          [self.navigationController popViewControllerAnimated:YES];
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseData[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                          
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }];
    }
}


- (void)aaa{

   
}

- (void)clickBackButton{
    
    [self.navigationController popViewControllerAnimated:YES];
}





@end
